package com.qida.clm.core.network.request;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.qida.clm.core.network.response.DelegateResponse;
import com.qida.clm.core.utils.LogUtil;

import java.io.UnsupportedEncodingException;
import java.util.Map;

public class DelegateRequest extends Request<String> {

	private static final String TAG = DelegateRequest.class.getSimpleName();
	private IRequest<?> mBaseRequest;
	private Listener<String> mListener;
	private String mDumpParams;

	public DelegateRequest(String url, DelegateResponse response) {
		this(Method.POST, url, response);
	}

	public DelegateRequest(int method,String url,DelegateResponse response) {
		super(method, url, response);
		mListener = response;
	}

    @Override
    protected String convertParams(Map<String, ?> params, String paramsEncoding) {
    	String strParams = super.convertParams(params, paramsEncoding);
    	mDumpParams = String.format(getUrl()+"&%s", strParams);
    	return strParams;
    }

    public <T> void setClientRequest(IRequest<T> request){
    	this.mBaseRequest = request;
    }

	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		if(mBaseRequest != null){
			return mBaseRequest.getHeaders();
		}
		return super.getHeaders();
	}

	@Override
	protected Map<String, ?> getParams() throws AuthFailureError {
		if(mBaseRequest != null){
			return mBaseRequest.getParams();
		}
		return super.getParams();
	}

	@Override
	protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String parsed = null;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        LogUtil.i(TAG, "url:"+mDumpParams);
        LogUtil.i(TAG, "result:"+parsed);
        //我们需要在子线程中去解析数据,避开volley的ResponseDelivery机制.
        if(mListener != null){
        	mListener.onResponse(parsed);
        }
		return Response.success(parsed,HttpHeaderParser.parseCacheHeaders(response));
	}

	@Override
	protected void deliverResponse(String response) {}
}